<template>
  <div class="container">
    <el-row :gutter="10">
      <el-col :span="4">
        <div class="card-container">
          <el-card :body-style="{ padding: '5px' }" shadow="never">
            <template #header>
              <div class="card-header">
                <span class="card-title">分类</span>
              </div>
            </template>
            <div class="card-content-full">
              <el-tree
                ref="dictTypeTreeRef"
                accordion
                :check-strictly="true"
                class="custom-tree"
                :data="typeTree.dataList"
                highlight-current
                node-key="id"
                :props="typeTree.props"
                :show-checkbox="false"
                @node-click="handleDictTypeClick"
              />
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card-container">
          <el-card :body-style="{ padding: '5px' }" shadow="never">
            <template #header>
              <div class="card-header">
                <el-row :gutter="10" style="width: 100%" align="middle">
                  <el-col :span="8">
                    <span class="card-title">字典</span>
                  </el-col>
                  <el-col :span="16">
                    <div class="card-btn">
                      <div>
                        <el-button
                          icon="Remove"
                          v-auth="['dict/sc']"
                          type="warning"
                          @click="handleDictDelete"
                        >
                          删除
                        </el-button>
                      </div>
                      <div>
                        <el-button
                          icon="Plus"
                          v-auth="['dict/xz']"
                          type="primary"
                          @click="handleDictAdd"
                        >
                          新增
                        </el-button>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </template>
            <div class="card-content-full">
              <el-scrollbar>
                <div style="display: flex; align-items: center">
                  <el-input
                    v-model="state.searchKey"
                    clearable
                    placeholder="输入名称/编码搜索"
                    prefix-icon="search"
                  />
                  <el-button
                    type="primary"
                    icon="search"
                    @click="handleSearchQuery"
                  />
                </div>
                <el-tree
                  ref="dictTreeRef"
                  accordion
                  :check-strictly="true"
                  class="custom-tree"
                  :data="dictTree.dataList"
                  :default-expanded-keys="state.dictTreeExpanderKeys"
                  highlight-current
                  node-key="id"
                  :props="dictTree.props"
                  show-checkbox
                  @node-click="handleDictClick"
                >
                  <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <span>[{{ data.dictTypeName }}]{{ node.label }}</span>
                      <span style="float: right">
                        <el-button
                          v-auth="['dict/xg']"
                          size="small"
                          type="primary"
                          @click="handleDictEdit(data)"
                        >
                          修改
                        </el-button>
                      </span>
                    </span>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="14">
        <el-card :body-style="{ padding: '10px' }" shadow="never">
          <template #header>
            <span class="card-title">字典项</span>
          </template>
          <vab-query-form>
            <vab-query-form-left-panel :span="24">
              <el-button
                v-auth="['dict/xzzdx']"
                icon="circle-plus"
                type="primary"
                @click="handleDictEntryAdd"
              >
                添加
              </el-button>
              <el-button
                icon="Remove"
                v-auth="['dict/sczdx']"
                type="danger"
                @click="handleDictEntryDelete"
              >
                批量删除
              </el-button>
              <el-button
                icon="refresh"
                type="success"
                @click="handleDictEntryRefresh"
              >
                刷新缓存
              </el-button>
            </vab-query-form-left-panel>
          </vab-query-form>

          <el-table
            ref="dictEntryTableRef"
            v-loading="tableOptions.loading"
            border
            stripe
            :data="tableOptions.dataList"
            :height="tableOptions.height"
            :cell-style="tableStyle.cellStyle"
            :header-cell-style="tableStyle.headerCellStyle"
            @sort-change="handleSortChange"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
          >
            <el-table-column
              align="center"
              show-overflow-tooltip
              type="selection"
              width="50"
            />
            <el-table-column label="序号" type="index" width="55">
              <template #default="{ $index }">
                {{ $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="字典编码"
              prop="dictCode"
              width="140"
            />
            <el-table-column
              align="center"
              label="字典项值"
              prop="dictValue"
              width="100"
            />
            <el-table-column
              align="center"
              label="字典项内容"
              prop="dictText"
              width="140"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="是否只读"
              prop="isReadonly"
              width="90"
            />
            <el-table-column
              align="center"
              label="排序号"
              prop="orderId"
              width="80"
            />
            <el-table-column
              align="center"
              :formatter="dateFormat"
              label="创建时间"
              prop="createTime"
              width="120"
            />
            <el-table-column
              align="center"
              label="备注"
              prop="remark"
              width="180"
            />
            <el-table-column
              align="center"
              fixed="right"
              label="操作"
              prop="operation"
              width="180"
            >
              <template #default="{ row }">
                <el-button
                  v-auth="['dict/xgzdx']"
                  size="small"
                  type="warning"
                  @click="handleDictEntryEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-auth="['dict/sczdx']"
                  size="small"
                  type="danger"
                  @click="handleDictEntryDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            :current-page="tableOptions.pagination.current"
            :layout="tableOptions.pagination.layout"
            :page-size="tableOptions.pagination.size"
            :total="tableOptions.pagination.total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-card>
      </el-col>
    </el-row>
    <dict-edit ref="dictEditRef" width="50%" @confirm="handleDictEditConfirm" />
    <dict-entry-edit
      ref="dictEntryEditRef"
      width="50%"
      @confirm="handleEntryEditConfirm"
    />
  </div>
</template>
<script setup name="Dict">
import { useMessage, useMessageBox } from "@/hooks/message";
import {
  queryDictTree,
  queryEntryTable,
  deleteDictEntry,
  deleteDict,
  refreshDictEntry
} from "@/api/admin/system/dict/";
import { querySystemTreeNode } from "@/api/admin/system/systemtree";
import { dateFormat } from "@/utils/common";
import { getTableHeight } from "@/utils/util";
import dictEntryEdit from "./components/dictEntryEdit.vue";
import dictEdit from "./components/dictEdit.vue";
import { useTable } from "@/hooks/table";
import { useTree } from "@/hooks/tree";
import { useTree as useDictTree } from "@/hooks/tree";

const dictTypeTreeRef = ref(null);
const dictTreeRef = ref(null);
const dictEditRef = ref(null);
const dictEntryEditRef = ref(null);
const dictEntryTableRef = ref(null);

const state = reactive({
  dictTreeExpanderKeys: [],
  dictCount: 0,
  dictTypeCode: "",
  dictCode: "",
  searchKey: ""
});

const treeOptions = reactive({
  queryForm: { treeCode: "dict" },
  props: {
    children: "children",
    label: "text"
  },
  queryFunction: querySystemTreeNode
});

const { instance: typeTree, queryTreeData: queryDictTypeTreeData } = useTree(
  treeOptions,
  dictTypeTreeRef
);

const dictTreeOptions = reactive({
  queryForm: { dictTypeCode: "", ascs: "order_id" },
  props: {
    children: "children",
    label: "text",
    isLeaf: "leaf"
  },
  queryFunction: queryDictTree,
  onLoaded: function () {
    if (dictTree.dataList.length > 0) {
      state.dictTreeExpanderKeys = state.dictTreeExpanderKeys.concat(
        dictTree.dataList[0].id
      );
    }
  }
});

const { instance: dictTree, queryTreeData: queryDictTreeData } = useDictTree(
  dictTreeOptions,
  dictTreeRef
);

const tableOptions = reactive({
  height: getTableHeight(0, true, true) - 95,
  queryForm: {
    dictCode: ""
  },
  queryFunction: queryEntryTable,
  ascs: ["order_id"]
});

const {
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange
} = useTable(tableOptions, dictEntryTableRef);

onMounted(() => {
  queryDictTypeTreeData();
  queryDictTreeData();
});

const handleDictTypeClick = data => {
  state.dictTypeCode = data.nodeCode;
  const params = {};
  params.dictTypeCode = data.nodeCode;
  queryDictTreeData(params);
};

const handleHeight = () => {
  state.height = getTableHeight(1) - 60 - 60 - 10;
};

onBeforeMount(() => {
  window.addEventListener("resize", handleHeight);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleHeight);
});

const handleSearchQuery = async () => {
  dictTreeOptions.dataList = [];
  const params = {};
  if (state.searchKey) {
    params.searchKey = state.searchKey;
    params.ascs = "order_id";
    queryDictTreeData(params);
  } else {
    queryDictTreeData();
  }
};

const handleDictEditConfirm = () => {
  const params = {};
  params.dictTypeCode = state.dictTypeCode;
  queryDictTreeData(params);
};

const handleEntryEditConfirm = () => {
  queryTableData();
};

const handleDictClick = data => {
  if (data.dictCode) {
    state.dictCode = data.dictCode;
    queryTableData({ dictCode: data.dictCode }, true);
  }
};

const handleDictDelete = () => {
  const checkedNodes = dictTreeRef.value.getCheckedNodes();
  if (checkedNodes.length < 1) {
    useMessage().warning("未选中任何字典");
  } else {
    const items = checkedNodes.filter(item => item.ifAllowDelete != "N");
    console.log(items.length);
    if (items.length > 0) {
      useMessageBox()
        .confirm("删除的字典将无法恢复，是否继续")
        .then(() => {
          const ids = checkedNodes.map(item => item.id).join();
          deleteDict(ids).then(res => {
            if (res.code === 200) {
              useMessage().success("删除成功");
              const params = {};
              params.dictTypeCode = state.dictTypeCode;
              queryDictTreeData(params);
            } else {
              useMessage().success(res.msg);
            }
          });
        });
    } else {
      useMessage().warning("选中的字典均不允许删除");
    }
  }
};

const handleDictEntryRefresh = async () => {
  const loadingInstance = ElLoading.service({ fullscreen: true });
  const { code, msg } = await refreshDictEntry();
  if (code === 200) {
    useMessage().success(msg);
  } else {
    useMessage().error(msg);
  }
  if (loadingInstance) loadingInstance.close();
};

const handleDictEdit = node => {
  console.log("handleDictEdit", node);
  if (node) {
    if (node.isReadonly === "Y") {
      useMessage().warning("字典只读,不能编辑");
    } else {
      dictEditRef.value.show(node);
    }
  } else {
    useMessage().warning("未选中任何字典");
  }
};

const handleDictAdd = () => {
  dictEditRef.value.show();
};

const handleDictEntryAdd = () => {
  const row = {};
  row.dictCode = state.dictCode;
  dictEntryEditRef.value.show(row);
};

const handleDictEntryEdit = row => {
  if (row.id) {
    dictEntryEditRef.value.show(row);
  } else {
    useMessage().warning("字典项主键不能为空");
  }
};

const handleDictEntryDelete = row => {
  if (row && row.id) {
    if (row.isReadonly === "Y") {
      useMessage().warning("字典项只读,不能删除");
    } else {
      useMessageBox()
        .confirm("删除的字典项将无法恢复，是否继续")
        .then(() => {
          deleteDictEntry(row.id).then(res => {
            if (res.code && res.code === 200) {
              useMessage().success(res.msg);
              queryTableData();
            } else {
              useMessage().error(res.msg);
            }
          });
        });
    }
  } else {
    if (tableOptions.dataSelections.length > 0) {
      const items = tableOptions.dataSelections.filter(
        item => item.isReadonly === "N"
      );
      console.log(items);
      if (items.length > 0) {
        const ids = items
          .map(item => {
            if (item.isReadonly === "N") {
              return item.id;
            }
          })
          .join();
        console.log(items);
        useMessageBox()
          .confirm("删除的字典项将无法恢复，是否继续")
          .then(() => {
            deleteDictEntry(ids).then(res => {
              if (res.code && res.code === 200) {
                useMessage().success(res.msg);
                queryTableData();
              } else {
                useMessage().error(res.msg);
              }
            });
          });
      } else {
        useMessage().warning("选中的字典项均为只读,不能删除");
      }
    } else {
      useMessage().warning("未选中任何行");
    }
  }
};
</script>

<style lang="scss" scoped>
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
}
</style>
